package ch8;

import util.Debug;
import util.Tools;

import java.util.Scanner;

/**
 * 使用PauseControl来实现暂停与恢复的Demo
 */

public class ThreadPauseDemo {
    final static PauseControl pc = new PauseControl();

    public static void main(String[] args) {
        final Runnable action = new Runnable() {
            @Override
            public void run() {
                Debug.info("Master, I'm working...");
                Tools.randomPause(300);
            }
        };

        Thread slave = new Thread() {
            @Override
            public void run() {
                try {
                    for (;;) {
                        pc.pauseIfNecessary(action);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        slave.setDaemon(true);
        slave.start();
        askOnBehaveOfSlave();
    }


    static void askOnBehaveOfSlave() {
        String answer;
        int minPause = 2000;
        try (Scanner sc = new Scanner(System.in)) {
            for (;;) {
                // 在最小和最大暂停时间之间选择一个暂停时间
                Tools.randomPause(8000, minPause);
                pc.requestPause();
                Debug.info("Master, may I take a rest now?%n");
                Debug.info("%n(1) OK, you may take a rest%n" + "(2) No, Keep working!%nPress any other key to quit:%n");
                answer = sc.next();
                if ("1".equals(answer)) {
                    pc.requestPause();
                    Debug.info("Thank you, may master!");
                    minPause = 8000;
                } else if ("2".equals(answer)) {
                    Debug.info("Yes, my master!");
                    pc.proceed();
                    minPause = 2000;
                } else {
                    break;
                }
            }
        }
        Debug.info("Game over!");
    }
}
